package com.jy.wms.controller;

import com.github.pagehelper.Page;
import com.joyi.gate.comm.SessionInfo;
import com.joyi.gate.safety.vo.UserInfo;
import com.jy.wms.common.SetStatus;
import com.jy.wms.common.base.BaseController;
import com.jy.wms.common.base.ReturnType;
import com.jy.wms.common.base.ServiceException;
import com.jy.wms.common.base.SucessException;
import com.jy.wms.common.mapUtils;
import com.jy.wms.pojo.SysLog;
import com.jy.wms.service.SysLogService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.UUID;

/**
 * @ClassName: SysLogController
 * @Description: TODO(这里用一句话描述这个类的作用)
 * @Author liyi
 * @Date Wed Sep 13 15:46:03 CST 2017
 */
@RestController
@RequestMapping("/file")
@Api(value = "/file", description = "关于文件操作")
public class FileController{

    @Value("${upload.file.location}")
    private String uploadLocation;

    @ApiOperation(value = "文件上传操作",response = JSONObject.class,notes = "文件上传操作")
    @PostMapping(value = "/upload")
    public @ResponseBody JSONObject upload(HttpServletRequest reqquest, @RequestParam("file") MultipartFile file) {

        JSONObject json=new JSONObject();
        json.put("stat","fail");
        json.put("fileName",null);
        json.put("filePath",null);
        json.put("msg","上传失败");
        try {
            if (file.isEmpty()) {
                json.put("stat","fail");
                json.put("fileName",null);
                json.put("filePath",null);
                json.put("msg","文件不能为空");
            }
            //String uploadDir = ResourceUtils.getURL("classpath:").getPath();
            //String uploadDir = reqquest.getSession().getServletContext().getRealPath("/")+"upload\\";
            String uploadDir = uploadLocation;
            File dir = new File(uploadDir);
            if(!dir.exists()) {
                dir.mkdirs();
            }
            String filename = file.getOriginalFilename();
            String suffix = filename.substring(filename.lastIndexOf("."));
            String defineName = UUID.randomUUID() + suffix;
            File serverFile = new File(uploadDir + filename);
            file.transferTo(serverFile);

            json.put("stat","success");
            json.put("fileName",filename);
            json.put("filePath",serverFile.getCanonicalPath());
            json.put("msg","上传成功");
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return json;
    }

    @ApiOperation(value = "文件下载操作",response = JSONObject.class,notes = "文件下载操作")
    @GetMapping(value = "/downLoadFile")
    public void downLoadFile(HttpServletResponse res, @RequestParam("fileName") String fileName) {
        InputStream ins = null ;
        BufferedInputStream bins = null;
        try {
            String path = uploadLocation + fileName;
            File file = new File(path);
            if (file.exists()) {
                 ins = new FileInputStream(path);
                 bins = new BufferedInputStream(ins);// 放到缓冲流里面
                OutputStream outs = res.getOutputStream();// 获取文件输出IO流
                BufferedOutputStream bouts = new BufferedOutputStream(outs);
                res.setContentType("application/x-download");// 设置response内容的类型
                res.setHeader(
                        "Content-disposition",
                        "attachment;filename="
                                + URLEncoder.encode(fileName, "UTF-8"));// 设置头部信息
                int bytesRead = 0;
                byte[] buffer = new byte[1024];
                // 开始向网络传输文件流
                while ((bytesRead = bins.read(buffer, 0, buffer.length)) != -1) {
                    bouts.write(buffer, 0, bytesRead);
                }
                bouts.flush();// 这里一定要调用flush()方法
                outs.close();
                bouts.close();
            }
        } catch (IOException e) {

        }finally {
            if(ins !=null){
                try {
                    ins.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(bins !=null){
                try {
                    bins.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }


    }
}